#include "tds_conn.h"

void mssql_create_table(MSSQL_CONN* conn, char* table_name)
{
	char sql[30000]; //memset(sql, 0, 30000);
	sprintf(sql, 
		"if not exists (select * from sysobjects where id = object_id('%s') and OBJECTPROPERTY(id, 'IsUserTable') = 1 ) \
			CREATE TABLE %s(\
		    clnt_addr        VARCHAR(16),\
		    clnt_user        VARCHAR(16),\
		    time_tz          VARCHAR(32),\
		    request_type     VARCHAR(8),\
		    request          VARCHAR(6000),\
		    request_bytes    INT,\
		    return_code      INT,\
		    reply_bytes      INT,\
		    url              VARCHAR(3500),\
		    url_bytes        INT,\
		    website          VARCHAR(64),\
		    clnt_type        VARCHAR(2000),\
		    clnt_type_bytes  INT)", 
		    table_name, table_name);

 	dbcmd(conn->dbprocess, sql);                             //将刚刚组装好的sql命令, 使用dbcmd命令保存到数据库连接句柄的缓存中  
                              
    if(dbsqlexec(conn->dbprocess) == FAIL)                        //如果执行的命令失败  
    {   
        dbclose(conn->dbprocess);                                 //关闭数据库操作进程  
        exit(EXIT_FAILURE);                            
    }  
}

/**
  * @brief  数据插入操作
  * @Notes  JSON数据字段需要使用专用的 字符串连接函数 strcat_json
  * 		字段数据使用双引号避免数据内包含单引号字符
  *			如果字段数据中包含双引号字符，只能使用个专用字符串处理函数，
  *			将原始数据(字符串)中的双引号字符前面添加一个反斜线转移符号\
  * @param  conn, 
  * @retval void
  */
void mssql_insert_table(struct __access_log_data_line_type* line,
					MSSQL_CONN* conn, char* table)
{
	char sql[30000];
	sprintf(
			sql, 
			"INSERT INTO %s value("
			"\"%s\", "	//clnt_addr
			"\"%s\", "	//clnt_user
			"\"%s\", "	//time_tz
			"\"%c\", "	//request_type: 'G' -> GET  'P' -> POST
			"\"%s\", "	//request: resource file or URL parameters.
			"\"%d\", "	//request_bytes
			"\"%d\", "	//return_code
			"\"%d\", "	//reply_bytes
			"\"%s\", "	//url
			"\"%d\", "	//url_bytes
			"\"%s\", "	//website
			"\"%s\", "	//clnt_type
			"\"%d\");",	//clnt_type_bytes
			table,
			line->clnt_addr,
			line->clnt_user,
			line->time_tz,
			line->request_type,	
#ifdef ADD_FIELD_request
			//(line->request_bytes > 6000)?"req":line->request,
			line->request,
#else
			"req", 		
#endif	
			line->request_bytes,
			line->return_code,
			line->reply_bytes,
#ifdef ADD_FIELD_url
			//(line->url_bytes > 3500)?"url":line->url,
			line->url,
#else
			"url",
#endif
			line->url_bytes,
			line->website,
#ifdef ADD_FIELD_clnt_type
			line->clnt_type,
#else
			"clnt",
#endif
			line->clnt_type_bytes
			);
	//printf("%s\n", sql);
	
 	dbcmd(conn->dbprocess, sql);                             //将刚刚组装好的sql命令, 使用dbcmd命令保存到数据库连接句柄的缓存中  
                              
    if(dbsqlexec(conn->dbprocess) == FAIL)                        //如果执行的命令失败  
    {   
        dbclose(conn->dbprocess);                                 //关闭数据库操作进程  
        exit(EXIT_FAILURE);                            
    }  

}
